/**
 * AI插件 - 提供AI生成功能集成
 */
import * as fabricjs from 'fabric';
const { fabric } = fabricjs;
import { v4 as uuidv4 } from 'uuid';

export default class AIPlugin {
    static pluginName = 'AIPlugin';
    static apis = ['generateImage', 'applyImg2Img', 'addGeneratedImageToCanvas'];

    constructor(canvas, editor, options = {}) {
        this.canvas = canvas;
        this.editor = editor;
        this.apiUrl = options.apiUrl || '/api/ai';
        this.loading = false;
    }

    // 文生图功能
    async generateImage(params) {
        if (this.loading) return null;

        this.loading = true;
        this.editor.emit('ai:generationStarted', params);

        try {
            const response = await fetch(`${this.apiUrl}/text2img`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            if (!response.ok) {
                throw new Error('AI生成失败');
            }

            const data = await response.json();
            this.editor.emit('ai:generationComplete', data);

            return data;
        } catch (error) {
            this.editor.emit('ai:generationError', error);
            console.error('AI生成错误:', error);
            return null;
        } finally {
            this.loading = false;
        }
    }

    // 图生图功能
    async applyImg2Img(imageData, params) {
        if (this.loading) return null;

        this.loading = true;
        this.editor.emit('ai:img2imgStarted', params);

        try {
            const formData = new FormData();
            formData.append('image', imageData);
            formData.append('params', JSON.stringify(params));

            const response = await fetch(`${this.apiUrl}/img2img`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error('图生图处理失败');
            }

            const data = await response.json();
            this.editor.emit('ai:img2imgComplete', data);

            return data;
        } catch (error) {
            this.editor.emit('ai:img2imgError', error);
            console.error('图生图错误:', error);
            return null;
        } finally {
            this.loading = false;
        }
    }

    // 将生成的图像添加到画布
    addGeneratedImageToCanvas(imageUrl) {
        return new Promise((resolve, reject) => {
            fabric.Image.fromURL(imageUrl, (img) => {
                // 调整图像大小以适合画布
                const maxDim = 300;
                if (img.width > maxDim || img.height > maxDim) {
                    if (img.width > img.height) {
                        img.scaleToWidth(maxDim);
                    } else {
                        img.scaleToHeight(maxDim);
                    }
                }

                img.set({
                    left: 100,
                    top: 100,
                    name: 'AI生成图像',
                    id: `ai-image-${Date.now()}`
                });

                this.canvas.add(img);
                this.canvas.setActiveObject(img);
                this.canvas.renderAll();

                this.editor.emit('ai:imageAddedToCanvas', img);
                resolve(img);
            }, (err) => {
                console.error('加载图像失败:', err);
                reject(err);
            });
        });
    }
}